const db = require("../db/index")
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('../config')
// 注册新用户
exports.regUser = (req, res) => {
    const userinfo = req.body
    // if (!userinfo.username || !userinfo.password) {
    //    return res.cc('账号或密码不能为空!')
    // }
    const sqlStr = 'select * from  ev_users where username=?'
    db.query(sqlStr, userinfo.username, (err, results) => {//select语句返回的结果是数组形式
        if (err) {
            return res.cc(err)
        }
        if (results.length > 0) {
            return res.cc('用户名已被注册!')
        }
        userinfo.password = bcrypt.hashSync(userinfo.password, 10)
        const sql = 'insert into ev_users set ?'
        db.query(sql, { username: userinfo.username, password: userinfo.password }, (err, results) => {
            if (err) {
                return res.cc(err)
            }
            if (results.affectedRows !== 1) {
                return res.cc('注册用户失败,请稍后再试!')
            }

            res.cc('注册成功', 0)
        })
    })
}

// 登录处理
exports.login = (req, res) => {
    const userinfo = req.body
    const sql = 'select * from ev_users where username=?'
    db.query(sql, userinfo.username, (err, results) => {
        if (err) return res.cc(err)
        if (results.length !== 1) return res.cc('登录失败!')
        const compareSync = bcrypt.compareSync(userinfo.password, results[0].password)//比较用户提交与库的密码是否一致 返回布尔值
        if (!compareSync) return res.cc('密码错误,请重新输入!')
        const user = { ...results[0], username: '', password: '' }
        const tokenStr = jwt.sign(user, config.jwtSecretKey, { expiresIn: config.expiresIn })
        res.send({
            status: 0,
            msg: '登录成功',
            token: 'Bearer' + tokenStr
        })
    })
}
